package com.example.myapplication11_3;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.app.ProgressDialog;
import android.os.Handler;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main); // 设置布局文件
        Button btnProgressDialog = findViewById(R.id.btn_progress_dialog); // 获取按钮控件
        btnProgressDialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showProgressDialog(); // 点击按钮时显示进度条对话框
            }
        });
    }

    /**
     * 显示水平进度条对话框，模拟加载过程，加载完成后自动关闭
     */
    private void showProgressDialog() {
        final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); // 设置为水平进度条样式
        progressDialog.setTitle("正在加载中"); // 设置标题
        progressDialog.setMax(100); // 设置最大进度
        progressDialog.setProgress(0); // 初始化进度为0
        progressDialog.setCancelable(false); // 禁止手动取消
        progressDialog.show(); // 显示对话框

        final Handler handler = new Handler();
        new Thread(new Runnable() {
            int progress = 0;
            @Override
            public void run() {
                while (progress < 100) {
                    progress += 1; // 每次增加1
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            progressDialog.setProgress(progress); // 更新进度条
                        }
                    });
                    try {
                        Thread.sleep(30); // 模拟加载耗时
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        progressDialog.dismiss(); // 加载完成后关闭对话框
                    }
                });
            }
        }).start();
    }
}